﻿package com.singlenotion.form 
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import gs.TweenLite;
	
	/**
	 * ...
	 * @author Adam Jowett (Single Notion)
	 */
	public class FormFieldBackground extends MovieClip
	{
		private var _bgWidth:Number;
		private var _bgHeight:Number;
		private var _bgColour:int;
		private var _borderColour:int;
		private var _errorColour:int;
		private var _focusColour:int;
		
		private var _border:Sprite;
		private var _bg:Sprite;
		
		private var _valid:Boolean;
		private var _focus:Boolean;
		
		public function FormFieldBackground($bgWidth:Number, $bgHeight:Number, $bgColour:int = 0xFFFFFF, $borderColour:int = 0x000000,
											$focusColour:int = 0xD0E925, $errorColour:int = 0x990000) 
		{
			_bgWidth = $bgWidth;
			_bgHeight = $bgHeight;
			_bgColour = $bgColour;
			_borderColour = $borderColour;
			_errorColour = $errorColour;
			_focusColour = $focusColour;
			
			init(null);
		}
		
		private function init($e:Event):void 
		{
			addEventListener(Event.REMOVED_FROM_STAGE, destroy, false, 0, true);
			
			drawBackground();
			drawBorder();
		}
		
		private function drawBackground():void
		{
			_bg = new Sprite();
			_bg.graphics.beginFill(_bgColour, 1);
			_bg.graphics.drawRect(0, 0, _bgWidth, _bgHeight);
			_bg.graphics.endFill();
			
			addChild(_bg);
		}
		
		private function drawBorder():void
		{
			_border = new Sprite();
			_border.graphics.lineStyle(1, _borderColour, 1);
			_border.graphics.drawRect(0, 0, _bgWidth, _bgHeight);
			
			addChild(_border);
		}
		
		public function highlightError():void
		{
			TweenLite.to(_border, 0.3, { tint:_errorColour } );
		}
		
		public function reset():void
		{
			TweenLite.to(_border, 0.3, { removeTint:true } );
		}
		
		private function destroy($e:Event):void 
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, destroy);
		}
		
		public function get valid():Boolean { return _valid; }
		
		public function set valid(value:Boolean):void 
		{
			_valid = value;
			if (!_valid) highlightError(); else reset();
		}
		
		public function get focus():Boolean { return _focus; }
		
		public function set focus(value:Boolean):void 
		{
			_focus = value;
			if (_focus) TweenLite.to(_bg, 0.3, { tint:_focusColour } ); else TweenLite.to(_bg, 0.3, { removeTint:true } );
		}
	}
}